from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView
from goods.models import GoodsCategory, GoodsChannel, GoodsChannelGroup
from collections import OrderedDict
from contents.models import ContentCategory, Content

# Create your views here.

class IndexView(View):
    def get(self, request):

        # 准备字典 有序字典
        categories = OrderedDict()
        # 查询并展示商品频道和分类
        # 查询频道
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')

        for channel in channels:
            # 查询频道组
            group_id = channel.group_id
            if group_id not in categories:
                categories[group_id] = {'channels': [], 'sub_cats': []}
            # 查询当前频道下的一级类别
            cat1 = channel.category
            categories[group_id]['channels'].append({'id': cat1.id, 'name': cat1.name, 'url': channel.url})
            # 查询当前一级类别下的二级类别
            sub_cats = GoodsCategory.objects.filter(parent_id=cat1.id)
            for sub_cat in sub_cats:
                categories[group_id]['sub_cats'].append({'id': sub_cat.id, 'name': sub_cat.name, 'sub_cats': []})
                # 查询当前二级类别下的三级类别
                sub_sub_cats = GoodsCategory.objects.filter(parent_id=sub_cat.id)
                for sub_sub_cat in sub_sub_cats:
                    categories[group_id]['sub_cats'][-1]['sub_cats'].append(
                        {"id": sub_sub_cat.id, 'name': sub_sub_cat.name})



        # 查询广告数据
        # 查询广告的类别
        ContentCategorys = ContentCategory.objects.all()
        contents =OrderedDict()

        for cat in ContentCategorys:
            contents[cat.key] = Content.objects.filter(category=cat, status=True).order_by('sequence')


        context ={
            'categories': categories,
            'contents': contents
        }
        # 使用类别查询广告数据

        return render(request, 'index.html', context)




